/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hcbank.jpa.controllers;

import com.hcbank.jpa.controllers.exceptions.NonexistentEntityException;
import com.hcbank.jpa.controllers.exceptions.PreexistingEntityException;
import com.hcbank.jpa.controllers.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.hcbank.jpa.entities.AccountEntity;
import com.hcbank.jpa.entities.TransactionEntity;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author NHAHV
 */
public class TransactionEntityJpaController implements Serializable {

    public TransactionEntityJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(TransactionEntity transactionEntity) throws PreexistingEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            AccountEntity toAccount = transactionEntity.getToAccount();
            if (toAccount != null) {
                toAccount = em.getReference(toAccount.getClass(), toAccount.getId());
                transactionEntity.setToAccount(toAccount);
            }
            AccountEntity fromAccount = transactionEntity.getFromAccount();
            if (fromAccount != null) {
                fromAccount = em.getReference(fromAccount.getClass(), fromAccount.getId());
                transactionEntity.setFromAccount(fromAccount);
            }
            em.persist(transactionEntity);
            if (toAccount != null) {
                toAccount.getTransactionEntityList().add(transactionEntity);
                toAccount = em.merge(toAccount);
            }
            if (fromAccount != null) {
                fromAccount.getTransactionEntityList().add(transactionEntity);
                fromAccount = em.merge(fromAccount);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findTransactionEntity(transactionEntity.getId()) != null) {
                throw new PreexistingEntityException("TransactionEntity " + transactionEntity + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(TransactionEntity transactionEntity) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            TransactionEntity persistentTransactionEntity = em.find(TransactionEntity.class, transactionEntity.getId());
            AccountEntity toAccountOld = persistentTransactionEntity.getToAccount();
            AccountEntity toAccountNew = transactionEntity.getToAccount();
            AccountEntity fromAccountOld = persistentTransactionEntity.getFromAccount();
            AccountEntity fromAccountNew = transactionEntity.getFromAccount();
            if (toAccountNew != null) {
                toAccountNew = em.getReference(toAccountNew.getClass(), toAccountNew.getId());
                transactionEntity.setToAccount(toAccountNew);
            }
            if (fromAccountNew != null) {
                fromAccountNew = em.getReference(fromAccountNew.getClass(), fromAccountNew.getId());
                transactionEntity.setFromAccount(fromAccountNew);
            }
            transactionEntity = em.merge(transactionEntity);
            if (toAccountOld != null && !toAccountOld.equals(toAccountNew)) {
                toAccountOld.getTransactionEntityList().remove(transactionEntity);
                toAccountOld = em.merge(toAccountOld);
            }
            if (toAccountNew != null && !toAccountNew.equals(toAccountOld)) {
                toAccountNew.getTransactionEntityList().add(transactionEntity);
                toAccountNew = em.merge(toAccountNew);
            }
            if (fromAccountOld != null && !fromAccountOld.equals(fromAccountNew)) {
                fromAccountOld.getTransactionEntityList().remove(transactionEntity);
                fromAccountOld = em.merge(fromAccountOld);
            }
            if (fromAccountNew != null && !fromAccountNew.equals(fromAccountOld)) {
                fromAccountNew.getTransactionEntityList().add(transactionEntity);
                fromAccountNew = em.merge(fromAccountNew);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = transactionEntity.getId();
                if (findTransactionEntity(id) == null) {
                    throw new NonexistentEntityException("The transactionEntity with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            TransactionEntity transactionEntity;
            try {
                transactionEntity = em.getReference(TransactionEntity.class, id);
                transactionEntity.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The transactionEntity with id " + id + " no longer exists.", enfe);
            }
            AccountEntity toAccount = transactionEntity.getToAccount();
            if (toAccount != null) {
                toAccount.getTransactionEntityList().remove(transactionEntity);
                toAccount = em.merge(toAccount);
            }
            AccountEntity fromAccount = transactionEntity.getFromAccount();
            if (fromAccount != null) {
                fromAccount.getTransactionEntityList().remove(transactionEntity);
                fromAccount = em.merge(fromAccount);
            }
            em.remove(transactionEntity);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<TransactionEntity> findTransactionEntityEntities() {
        return findTransactionEntityEntities(true, -1, -1);
    }

    public List<TransactionEntity> findTransactionEntityEntities(int maxResults, int firstResult) {
        return findTransactionEntityEntities(false, maxResults, firstResult);
    }

    private List<TransactionEntity> findTransactionEntityEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(TransactionEntity.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public TransactionEntity findTransactionEntity(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(TransactionEntity.class, id);
        } finally {
            em.close();
        }
    }

    public int getTransactionEntityCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<TransactionEntity> rt = cq.from(TransactionEntity.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
